package com.learn.sb.redis.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisConfig {

	private RedisConnectionFactory connectionFactory = null;

	@Bean(name = "RedisConnectionFactory")
	public RedisConnectionFactory initRedisConnectionFactory() {
		if (this.connectionFactory != null) {
			return this.connectionFactory;
		}
		JedisPoolConfig poolConfig = new JedisPoolConfig();
		poolConfig.setMaxIdle(30);  // 最大空闲数
		poolConfig.setMaxTotal(50); // 最大连接数
		poolConfig.setMaxWaitMillis(2000);  // 最大等待毫秒数
		// 指定jedisPoolConifig来修改默认的连接池构造器（真麻烦，滥用设计模式！）
		JedisClientConfiguration.JedisPoolingClientConfigurationBuilder jpcb =
				(JedisClientConfiguration.JedisPoolingClientConfigurationBuilder) JedisClientConfiguration.builder();
		jpcb.poolConfig(poolConfig);
		// 通过构造器来构造jedis客户端配置
		JedisClientConfiguration jedisClientConfiguration = jpcb.build();

		// 单机版jedis
		RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
		redisStandaloneConfiguration.setHostName("10.10.139.42");
		redisStandaloneConfiguration.setPort(6379);
		redisStandaloneConfiguration.setDatabase(0);
		redisStandaloneConfiguration.setPassword("123456");

		// 单机配置 + 客户端配置 = jedis连接工厂
		RedisConnectionFactory connectionFactory = new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration);

		this.connectionFactory = connectionFactory;
		return connectionFactory;
	}

	@Bean(name = "RedisTemplate")
	public RedisTemplate<Object, Object> initRedisTemplate() {
		RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
		RedisSerializer stringRedisSerializer = redisTemplate.getStringSerializer();
//		// 设置 字符串序列化器，这样，Spring就会吧Redis的key当做字符串处理
//		redisTemplate.setKeySerializer(stringRedisSerializer);
//		redisTemplate.setHashKeySerializer(stringRedisSerializer);
//		// 设置 字符串序列化器，这样，Spring就会吧Redis的value当做字符串处理
//		redisTemplate.setValueSerializer(stringRedisSerializer);
//		redisTemplate.setHashValueSerializer(stringRedisSerializer);

		// 或设置所有的默认序列化器为 string
		redisTemplate.setDefaultSerializer(stringRedisSerializer);

		redisTemplate.setConnectionFactory(initRedisConnectionFactory());
		return redisTemplate;
	}
}
